package com.yz.antlr.csv.main;

import com.yz.antlr.csv.g4.CsvLexer;
import com.yz.antlr.csv.g4.CsvParser;
import com.yz.antlr.hello.impstand.HelloErrCheck;
import com.yz.antlr.hello.impstand.JCLAna;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStreamRewriter;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.aspectj.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author yanzhao
 * @version 1.0
 * TODO
 * @date 2022/3/24 19:18
 */
public class CsvAntlrMain {
    private static final Logger log = LoggerFactory.getLogger(CsvAntlrMain.class);

    public void execMath(String str) {
        CharStream input = CharStreams.fromString(str);

        // 将内容传递到词法解析器
        CsvLexer lexer = new CsvLexer(input);

        // 传递到流
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);

        //获取到g4捕获到所有内容
        TokenStreamRewriter tokenStreamRewriter = new TokenStreamRewriter(tokenStream);

        //将流传递到语法解析器
        CsvParser parser = new CsvParser(tokenStream);

        // 添加错误回调函数
        parser.addErrorListener(new HelloErrCheck());

        //两个方法都能生成树，但是prog会报结尾错误，具体原因不详
//        ParseTree tree = parser.prog();
        ParseTree tree = parser.compilatin_unit();

        System.out.println(tree.toStringTree());

        //创建树遍历器
        ParseTreeWalker parseTreeWalker = new ParseTreeWalker();

        //添加自定义解析器
        JCLAna jclAna = new JCLAna(tokenStreamRewriter);

        // 添加树和自定义解析器到
        parseTreeWalker.walk(jclAna, tree);

        // 输出打印最终的内容
        System.out.println(tokenStreamRewriter.getText());
    }

    public static void main(String[] args) throws IOException {
        String encoding = StandardCharsets.UTF_8.toString();
        CsvAntlrMain antlrMain = new CsvAntlrMain();

        String Path = "src/main/resources/test.csv";
        File file = new File(Path);
        String str = FileUtil.readAsString(file);
        antlrMain.execMath(str);

    }
}
